package com.klst.opennlp;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.logging.Logger;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class TigerSentenceSource extends PipedOutputStream implements Runnable {
  
  private final static Logger LOG = Logger.getLogger(TigerSentenceSource.class.getName());
  
  PipedInputStream sinkPis = null;
  
  InputSource xmlInputSource = null;
  DefaultHandler tigerContentEventHandler = null;
  XMLReader xmlReader; 
  
  public TigerSentenceSource(PipedInputStream snk, File file) throws IOException {
    this(snk, new FileInputStream(file));
  }

  public TigerSentenceSource(PipedInputStream snk, InputStream inputStream) throws IOException {
    super(snk);
    LOG.info("ctor inputStream="+inputStream);
    this.sinkPis = snk;
    this.xmlInputSource = new InputSource(inputStream);
    this.tigerContentEventHandler = new TigerContentEventHandler(this);
    try {
      this.xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
      this.xmlReader.setContentHandler(tigerContentEventHandler);
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    }
  }

  public void write(int b)  throws IOException {
//    LOG.info("write b="+b);
    super.write(b);
  }

  public void write(byte b[], int off, int len) throws IOException {
//    LOG.info("write b="+b + ", off="+off + ", len="+len);
    super.write(b, off, len);
  }

  public synchronized void flush() throws IOException {
//    LOG.info("flush ********************************************** no sleep");
    super.flush();
//    try {
//      Thread.sleep( 200 );
//    } catch (InterruptedException e) {
//      e.printStackTrace();
//    }
  }


  @Override
  public void run() {
    LOG.info("start parsing");
    try {
      this.xmlReader.parse(this.xmlInputSource);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } finally {
      try {
        this.flush();
        this.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  
}